package cn.online.zhuanshenben.web;


import cn.online.zhuanshenben.entity.Suser;
import cn.online.zhuanshenben.service.SuserService;
import cn.online.zhuanshenben.util.Md5Utils;
import cn.online.zhuanshenben.vo.Result;
import cn.online.zhuanshenben.util.StrUtil;
import cn.online.zhuanshenben.vo.Page;
import com.alibaba.fastjson2.JSON;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @author oldliu
 * @since 1.0
 */
//*.d
@WebServlet("*.do")
public class CommonServlet extends BaseServlet {

    //
    protected Page<Suser> users(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
        int page = StrUtil.toInt(req.getParameter("page"), 1);
        if(page<1)
            throw  new RuntimeException("page小于1");
        int limit = StrUtil.toInt(req.getParameter("limit"), 10);
        String name = req.getParameter("sname");
        String phone = req.getParameter("phone");
        String school = req.getParameter("school");
        String major = req.getParameter("major");
        Page<Suser> search = SuserService.ME.search(phone, name, school, major, page, limit);
        return search;
    }

    protected Result addUser(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
        Suser user = new Suser();
        //md5
        user.setPass(Md5Utils.hash(req.getParameter("pass")));
        user.setSname(req.getParameter("sname"));
        user.setSchool(req.getParameter("school"));
        user.setPhone(req.getParameter("phone"));
        user.setMajor(req.getParameter("major"));
        user.setSex(req.getParameter("sex"));
        user.setType(req.getParameter("type"));
        user.setIsgraduate("1".equals(req.getParameter("isgraduate")));
        user.setAddtime(new Date());
        int rtn = SuserService.ME.add(user);
        return rtn > 0 ? Result.success() : Result.error("增加失败");
    }

    protected Result finduser(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
        Long id = StrUtil.toLong(req.getParameter("id"), -1);
        Suser suser = SuserService.ME.get(id);
        return suser != null ? Result.success(suser) : Result.error("用户不存在！");
    }

    protected Result batchDelUser(HttpServletResponse resp, HttpServletRequest req) throws ServletException,
            IOException {
        String ids = req.getParameter("ids");
        String[] split = ids.split(",");
        long id[] = new long[split.length];
        for (int i = 0; i < id.length; i++) {
            id[i] = Long.parseLong(split[i]);
        }
        int res = SuserService.ME.batDel(id);
        return res > 0 ? Result.success() : Result.error("禁止删除！");
    }
}
